// 管理用户共享数据
// 开启命名空间
// 导入接口函数
import { loginAPI } from '@/api/user'
const userModules = {
  namespaced: true,
  state () {
    return {
      token: '',
      refreshToken: ''
    }
  },
  mutations: {

    setToken: (state, token) => {
      state.token = token
    },

    setRefreshToken: (state, refreshToken) => {
      state.refreshToken = refreshToken
    },

    // 移除token
    removeToken: (state) => {
      state.token = ''
    },

    // 移除refreshToken
    removeRefreshToken: (state) => {
      state.refreshToken = ''
    }
  },
  actions: {

    // 登录action(异步更新state)
    // { commit }是解构store里的commit属性
    loginAction: async ({ commit }, loginForm) => {
      // 发请求
      const resp = await loginAPI(loginForm)
      // 提交mutations,完成对state中属性的赋值
      commit('setToken', resp.data.token)
      commit('setRefreshToken', resp.data.refresh_token)
    },

    // 退出登录action(包装多个mutations)
    logoutAction: ({ commit }) => {
      commit('removeToken')
      commit('removeRefreshToken')
    }
  },
  getters: {
  }
}

export default userModules
